
import React, { useState, useEffect } from 'react';
import useStore from '@/store/index'
import { v4 as uuidv4 } from 'uuid';
import { searchVipApi } from '@/api/vip/vip'
import { Button, Card, Space, Form, Input, Select, message, Row, Modal ,Radio} from 'antd';
import { Table } from 'antd';
import { searchPackageApi ,goodsCumApi} from '@/api/package/package';
import { searchGoodsApi } from '@/api/goods/goods';
import { searchStaffApi } from '@/api/staff/staff';
const { Search } = Input;




const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 16,
    },
  },
};

const columns: any = [
  {
    title: '姓名',
    dataIndex: 'vipName',
    render: (text: string) => <a>{text}</a>,
  },
  {
    title: '电话',
    dataIndex: 'vipPhone',
  },
  {
    title: '等级',
    dataIndex: 'vipRank',
  },
  {
    title: '余额',
    dataIndex: 'money',
  },
  {
    title: '积分',
    dataIndex: 'score',
  },
];

const staffColumns: any = [

  {
    title: '员工姓名',
    dataIndex: 'staffName',
    render: (text: string) => <a>{text}</a>,
  },

]


const packageColumns: any = [
  {
    title: '套餐名',
    dataIndex: 'packageName',
    render: (text: string) => <a>{text}</a>,
  },
  {
    title: '价格',
    dataIndex: 'packagePrice',
  },

];
export default function GoodsCsm() {
  const [form] = Form.useForm();
  const [id, setId] = useState('')
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const userInfo = useStore<any>((state: any) => state.userInfo)
  // 套餐搜索结果
  const [packageData, setPackageData] = useState<any>();
  const [packageName, setPackageName] = useState<any>({
    packagePrice:0
  });
  // 会员搜索结果
  const [vipData, setVipData] = useState<any>();
  const [vipCum, setVipCum] = useState<any>({
    vipRank:''
  });
  // 商品搜索结果
  const [goodsData, setGoodsData] = useState<any>();
  const [goods, setGoods] = useState<any>([]);
  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
  // 员工信息
  const [staffData, setStaffData] = useState<any>();
  const [staffName, setStaffName] = useState<any>();
  // 结算
  const [cum, setCum] = useState<any>(0);
  const [cutCum, setCutCum] = useState<any>(0);
  const [getScore, setGetScore] = useState<any>(0);
  const [notes, setNotes] = useState<any>('备注');
  const [payWay, setPayWay] = useState<any>('余额');
  // 折扣力度
  // const [cut, setCut] = useState<any>(0);
  let cut = 0
  // 选择员工模态框
  const [isModalOpen, setIsModalOpen] = useState(false);
  useEffect(() => {
    setId(uuidv4())
    console.log('最新的值',goods);
    let num = 0
    // console.log(goods);
    goods.forEach((element: any) => {
        num += element.goodsPrice * 1*element.goodsNum
        // console.log(element.goodsPrice ,element.goodsNum );
      })
    // // // // 套餐总价格
    // // // // 商品总价格
    if (vipCum.vipRank == '黄金会员') {
      cut = 98 / 100
      // setCut(98/100)
    } else if (vipCum.vipRank == '铂金会员') {
      // setCut(95/100)
      cut = 95 / 100
    } else if (vipCum.vipRank == '砖石会员') {
      // setCut(90/100)
      cut = 90 / 100
    }
    console.log('折后价',packageName.packagePrice* cut);
    
    
    if(packageName!==''){
      setCum(packageName.packagePrice * 1 +num)
      setCutCum(packageName.packagePrice * 1 * cut +num*cut)
      setGetScore(packageName.packagePrice * 1 * cut / 10 +num *cut /10)
    }
  }, [goods,packageName])
  const onFinish = async (values: any) => {
    // 清空所有数据
    if(!id){
      return message.open({
        type: 'error',
        content: '请生成一个id',
      });
    }else if(!vipCum){
      return message.open({
        type: 'error',
        content: '请选择会员',
      });
    }else if(!packageName){
      return message.open({
        type: 'error',
        content: '请选择套餐',
      });
    }else if(!staffName){
      return message.open({
        type: 'error',
        content: '请选择员工',
      });
    }else {
      let params:any = {}
      params.id=id
      params.userId=vipCum.id
      params.userName=vipCum.vipName
      params.packageName=packageName.packageName
      params.packagePrice=packageName.packagePrice
      params.packageNum=1
      params.payWay=payWay
      params.staff = staffName.staffName
      params.totalPrice=cum
      params.cutPrice=cutCum
      params.getScore=getScore
      params.notes=notes
      params.goodsName =JSON.stringify( goods.map((item:any)=>{
        return item.goodsName
      }))
      params.goodsPrice =JSON.stringify( goods.map((item:any)=>{
        return item.goodsPrice
      }))
      params.goodsNum =JSON.stringify( goods.map((item:any)=>{
        return item.goodsNum
      }))
      let res:any = await goodsCumApi(params)
      console.log(res);
      if(res.code ==200){
        // 清空所有数据
        setVipData('')
        setVipCum('')
        setPackageData('')
        setPackageName('')
        setStaffName('')
        setCum(0)
        setCutCum(0)
        setGetScore(0)
        setSelectedRowKeys([])
        // 重新生成id
        setId(uuidv4())
        setGoods([])
        setGoodsData([])
        return message.open({
          type: 'success',
          content: res.msg,
        });
  }else{
    return message.open({
      type: 'error',
      content: res.msg,
    });
  }
    }
  };
  const searchVip = (value: any) => {
    console.log('关键字', value);
    let params = {
      keyWord: value,
      belongToShop: userInfo.storeId
    }
    if (!value) {
      setVipCum('')
      setSelectedRowKeys([]);
    }
    searchVipApi(params).then(searchRes => {
      if (searchRes.code == 200) {
        let newVip = searchRes.viplist.map((viplist_item) => {
          return {
            "id": viplist_item.id.substring(0, 6),
            'key': viplist_item.id,
            "vipName": viplist_item.vipName,
            "sex": viplist_item.sex,
            "vipPhone": viplist_item.vipPhone,
            "vipRank": viplist_item.vipRank,
            "money": viplist_item.money,
            "score": viplist_item.score,

          }
        })
        setVipData(newVip)

        message.open({
          type: 'success',
          content: searchRes.msg,
        });
      } else {
        setVipData('')
        message.open({
          type: 'error',
          content: searchRes.msg,
        });
      }
    })

  }

  const searchGoods = (value: any) => {
    let params = {
      keyWord: value,
      belongToShop: userInfo.storeId
    }
    searchGoodsApi(params).then(res => {
      console.log(res.goodsList);
      if (res.code == 200) {
        let newGoodsList = res.goodsList.map((item: any) => {
          return {
            key: item.id,
            id: item.id,
            goodsName: item.goodsName,
            goodsPrice: item.goodsPrice,
            goodsNum:1
          }
        })
        setGoodsData(newGoodsList)
        console.log('setGoodsData', goodsData);
        message.open({
          type: 'success',
          content: res.msg,
        });
      } else {
        message.open({
          type: 'error',
          content: res.msg,
        });
      }
    })
  }
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      console.log(`选中: ${selectedRowKeys}`, '选中数组: ', selectedRows.length);
      if (selectedRows.length > 1) {
        setVipCum(selectedRows[0])

      } else {
        setVipCum(selectedRows[0])
      }
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  }
  const goodsSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      if (!vipCum) {
        return message.open({
          type: 'error',
          content: '请先选择用户1',
        });
      }
      let temGoods=selectedRows
      setGoods(selectedRows)
      
      if (vipCum.vipRank == '黄金会员') {
        cut = 98 / 100
        // setCut(98/100)
      } else if (vipCum.vipRank == '铂金会员') {
        // setCut(95/100)
        cut = 95 / 100
      } else if (vipCum.vipRank == '砖石会员') {
        // setCut(90/100)
        cut = 90 / 100
      }
      let arr = temGoods.map((element:any) => {
        return element.goodsPrice *1 *element.goodsNum
      });
      let num = 0 
      for(let i = 0 ; i < arr.length ;i++){
        num += arr[i]
      }
      
      if(packageName !== ''){setCum(num + packageName.packagePrice*1)
      setCutCum(num * cut + packageName.packagePrice*1 *cut)
      setGetScore(num * cut / 10 + packageName.packagePrice*1 *cut/10)
      }else{
      setCum(num )
      setCutCum(num * cut)
      setGetScore(num * cut / 10 )
      }
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };
  const staffRowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      console.log(`选中: ${selectedRowKeys}`, '选中数组: ', selectedRows);
      if (selectedRows.length == 1) {
        setStaffName(selectedRows[0])
      } else if (selectedRows.length > 1) {
        setStaffName(selectedRows[0])
      } else if (selectedRows.length == 0) {
        setStaffName(selectedRows[0])
      }
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  const createUuid = () => {
    setId(uuidv4())
  }

  // 选择员工
  const handleOk = async () => {
    setIsModalOpen(false);

  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const selectStaff = async () => {
    setIsModalOpen(true);
    let searchParams = { keyWord: '理发部', belongToShop: userInfo.storeId }

    try {
      let searchRes = await searchStaffApi(searchParams)
      if (searchRes.code == 200) {
        let newStaffList = searchRes.staff.map((staff: any) => {
          return {
            id: staff.id,
            key: staff.id,
            staffName: staff.staffName,
            staffSex: staff.staffSex,
            staffPhone: staff.staffPhone,
            staffAge: staff.staffAge,
            position: staff.position,
            department: staff.department,
            belongToShop: userInfo.storeId
          }
        })
        console.log(newStaffList);

        setStaffData(newStaffList)
        console.log(staffData);

        message.success(searchRes.msg)
      } else {
        message.error(searchRes.msg)
      }
    } catch (error) {
      message.error('搜索失败' + error)

    }
  }
  const searchPackage = (value: any) => {
    let params = {
      keyWord: value,
      belongToShop: userInfo.storeId
    }
    if (!vipCum) {
      return message.open({
        type: 'error',
        content: '请先选择用户',
      });
    }
    searchPackageApi(params).then(res => {
      if (res.code == 200) {
        let newPackageList = res.packageList.map(item => {
          return {
            key: item.id,
            id: item.id,
            packageName: item.packageName,
            packagePrice: item.packagePrice
          }
        })

        setPackageData(newPackageList)
        console.log('packageData', packageData);
        message.open({
          type: 'success',
          content: res.msg,
        });
      } else {
        message.open({
          type: 'error',
          content: res.msg,
        });
      }
    })
  }
  const packOnSelectChange = (newSelectedRowKeys: React.Key[], selectedRows: any) => {
    console.log('pqckage changed: ', newSelectedRowKeys, selectedRows.length);
    if (selectedRows.length == 1) {
      setSelectedRowKeys(newSelectedRowKeys);
      setPackageName(selectedRows[0])
      if (!vipCum) {
        return message.open({
          type: 'error',
          content: '请先选择用户1',
        });
      }
      if (vipCum.vipRank == '黄金会员') {
        cut = 98 / 100
        // setCut(98/100)
      } else if (vipCum.vipRank == '铂金会员') {
        // setCut(95/100)
        cut = 95 / 100
      } else if (vipCum.vipRank == '砖石会员') {
        // setCut(90/100)
        cut = 90 / 100
      }
      let num = 0
      if(goods){
        goods.forEach((element: any) => {
          num += element.goodsPrice * 1*element.goodsNum
        })
      }
      setCum(selectedRows[0].packagePrice * 1 +num)
      setCutCum(selectedRows[0].packagePrice * cut +num*cut)
      setGetScore(selectedRows[0].packagePrice * cut / 10 +num *cut /10)
    } else if (selectedRows.length > 1) {
      return message.open({
        type: 'error',
        content: '请先取消之前勾选的选项',
      });
    } else if (selectedRows.length == 0) {
      setSelectedRowKeys([]);
      setPackageName('')
    }
  };

  const packRowSelection = {
    selectedRowKeys,
    onChange: packOnSelectChange,
  };
  const goodsColumns: any = [
    {
      title: '商品名',
      dataIndex: 'goodsName',
      render: (text: string) => <a>{text}</a>,
    },
    {
      title: '价格',
      dataIndex: 'goodsPrice',
    },
    {
      title: '商品减一',
      fixed: 'right',
      width: 90,
      render: (record:any) => <Button onClick={()=>{jian(record)}}>-</Button>,
    },
    {
      title: '商品数量',
      fixed: 'right',
      width: 90,
      render: (record:any) => <div>
        {record.goodsNum}
      </div>,
      
    },
    {
      title: '商品加一',
      fixed: 'right',
      width: 90,
      render: (record:any) => <Button onClick={()=>{jia(record)}}>+</Button>,
    },
  ];
  const jia = (e:any)=>{
    // 查看是否勾选
    const isExe = goods.find((item:any)=>{
      return item.id ==e.id
    })
    if(!isExe){
      return message.error('请先勾选')
    }else if(isExe.goodsNum >= 10){
      return message.error('最多加到10')
    }
    
    // 改了勾选的数据，不渲染需要改原数组
    let newGoods = goods.map((item:any) => {
      if(item.id == e.id){
        return {
          key: item.id,
          id: item.id,
          goodsName: item.goodsName,
          goodsPrice: item.goodsPrice,
          goodsNum:item.goodsNum + 1
        }
      }else{
        return {
          key: item.id,
          id: item.id,
          goodsName: item.goodsName,
          goodsPrice: item.goodsPrice,
          goodsNum:item.goodsNum
        }
      }
    });
    
    
    setGoods(newGoods)
    
    // // // // 修改数据源
    let oldGoodsData = goodsData
    for(let i = 0 ; i <oldGoodsData.length ; i++){
      for(let j = 0;j<newGoods.length;j++){
        if(oldGoodsData[i].id == newGoods[j].id){
          oldGoodsData[i].key = newGoods[j].key
          oldGoodsData[i].goodsName = newGoods[j].goodsName
          oldGoodsData[i].goodsPrice = newGoods[j].goodsPrice
          oldGoodsData[i].goodsNum = newGoods[j].goodsNum
        }
      }
    }
    // // console.log('新数据',oldGoodsData);

    
    
    
    

      }
  const jian = (e:any)=>{
    let tempGoods= goods
    // 查看是否勾选
    const isExe = tempGoods.find((item:any)=>{
      return item.id ==e.id
    })
    if(!isExe){
      return message.error('请先勾选')
    }else if(isExe.goodsNum <= 1){
      return message.error('最多减到1')
    }
    
    // 改了勾选的数据，不渲染需要改原数组
    let newGoods = tempGoods.map((item:any) => {
      if(item.id == e.id){
        return {
          key: item.id,
          id: item.id,
          goodsName: item.goodsName,
          goodsPrice: item.goodsPrice,
          goodsNum:item.goodsNum -1
        }
      }else{
        return {
          key: item.id,
          id: item.id,
          goodsName: item.goodsName,
          goodsPrice: item.goodsPrice,
          goodsNum:item.goodsNum
        }
      }
    });
    setGoods(newGoods)
    // 修改数据源
    let oldGoodsData = goodsData
    for(let i = 0 ; i <goodsData.length ; i++){
      for(let j = 0;j<newGoods.length;j++){
        if(goodsData[i].id == newGoods[j].id){
          goodsData[i].key = newGoods[j].key
          goodsData[i].goodsName = newGoods[j].goodsName
          goodsData[i].goodsPrice = newGoods[j].goodsPrice
          goodsData[i].goodsNum = newGoods[j].goodsNum
        }
      }
    }
    
      }
      const selectPayWay = (e:any)=>{
        console.log(e);
        setPayWay(e.target.value)
      }
  return (
    <div>

      <Space direction="vertical" size={16}>

        <Card size="small" title="选择会员" style={{ width: '100%' }}>
          <Form
            form={form}
            name="register"
            onFinish={onFinish}
            initialValues={{ residence: ['zhejiang', 'hangzhou', 'xihu'], prefix: '86' }}
            style={{ width: 600 }}
            scrollToFirstError
          >
            <div>
              <Search
                placeholder="手机号/会员卡号/姓名"
                allowClear
                enterButton="查询"
                style={{ width: 500 }}
                onSearch={searchVip}
              />
              <Button className='vip_btn' type="primary" >
                散客
              </Button>
            </div>
            <div style={{ display: 'flex', justifyContent: "space-between", marginTop: '10px' }}>
              <p>姓名：<span style={{ color: 'red' }}>{vipCum ? vipCum.vipName : 'XXX'}</span></p>
              <p>电话：<span style={{ color: 'red' }}>{vipCum ? vipCum.vipPhone : 'XXX'}</span></p>
              <p>等级：<span style={{ color: 'red' }}>{vipCum ? vipCum.vipRank : 'XXX'}</span></p>
              <p>余额：<span style={{ color: 'red' }}>{vipCum ? vipCum.money : 'XXX'}</span></p>
              <p>积分：<span style={{ color: 'red' }}>{vipCum ? vipCum.score : 'XXX'}</span></p>
            </div>
            <div>
              <Table
                rowSelection={{
                  type: 'radio',
                  ...rowSelection,
                }}
                columns={columns}
                dataSource={vipData}
                pagination={false}
                showHeader={false}
              />
            </div>
            <Row gutter={8}>

              <div>订单编号：</div>

              <Input disabled={true} value={id} />

              <Button block onClick={createUuid}>生成卡号</Button>
            </Row>

            <Row gutter={8}>

              <div>提成员工：</div>

              <Input disabled={true} value={staffName ? staffName.staffName : '请选择员工'} />

              <Button block onClick={selectStaff}>选择员工</Button>
            </Row>
            <div>
                <h2>请选择支付方式</h2>
              <Radio.Group onChange={selectPayWay} value={payWay}>
                <Space direction="vertical">
                  <Radio value={'余额'}>余额</Radio>
                  <Radio value={'微信'}>微信</Radio>
                  <Radio value={'支付宝'}>支付宝</Radio>
                </Space>
              </Radio.Group>
              </div>
            <Row gutter={8}>

              <div>备注：</div>

              <textarea onChange={(e) => setNotes(e.target.value)} value={notes} name="" id=""></textarea>
            </Row>

            <div style={{ display: 'flex', justifyContent: "space-between", marginTop: '30px' }}>
              <div style={{ color: 'red' }}>消费合计：{cum}</div>
              <div style={{ color: 'red' }}>折后金额：{cutCum}</div>
              <div style={{ color: 'red' }}>获得积分：{getScore}</div>
            </div>
            <Form.Item {...tailFormItemLayout}>
              <Button style={{ marginRight: '20px', marginTop: '20px' }} >
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                结算
              </Button>
            </Form.Item>
          </Form>

        </Card>

      </Space>
      <Space direction="vertical" size={16}>
        <Card  size="small" title="物品消费" style={{ width: '100%' }}>
          <div>
            <Search
              placeholder="套餐名称"
              allowClear
              enterButton="查询"
              style={{ width: 500 }}
              onSearch={searchPackage}
            />
          </div>
          <div style={{ display: 'flex', justifyContent: "space-between", marginTop: '10px' }}>
            <p>套餐名称：<span style={{ color: 'red' }}>{packageName ? packageName.packageName : 'XXX'}</span></p>
            <p>套餐价格：<span style={{ color: 'red' }}>{packageName ? packageName.packagePrice + '元' : 'XXX'}</span></p>
          </div>
          <div>
            <Table
              rowSelection={{
                type: 'radio',
                ...packRowSelection
              }}
              columns={packageColumns}
              dataSource={packageData}
              pagination={false}
              showHeader={false}
            />
          </div>
        </Card>
        <Card style={{ width: ' 100%' }}>
          <div>
            <Search
              placeholder="商品名称"
              allowClear
              enterButton="查询"
              style={{ width: 500 }}
              onSearch={searchGoods}
            />
          </div>
          <div>
            <Table
              rowSelection={{
                ...goodsSelection
              }}
              columns={goodsColumns
              }
              dataSource={goodsData}
              pagination={false}
            />
          </div>

        </Card>

      </Space>
      <Modal title="选择员工" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Table
          rowSelection={{
            type: selectionType,
            ...staffRowSelection,
          }}
          columns={staffColumns}
          dataSource={staffData}
          pagination={false}
          showHeader={false}
        />
      </Modal>
    </div>
  )
}